package com.huike.business.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huike.business.domain.TbBusiness;
import com.huike.business.domain.TbBusinessTrackRecord;
import com.huike.business.domain.vo.BusinessTrackVo;
import com.huike.business.mapper.TbBusinessTrackRecordMapper;
import com.huike.business.service.ITbBusinessService;
import com.huike.business.service.ITbBusinessTrackRecordService;
import com.huike.clues.mapper.SysDictDataMapper;
import com.huike.common.utils.SecurityUtils;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商机跟进记录Service业务层处理
 * 
 * @author wgl
 * @date 2021-04-28
 */
@Service
@RequiredArgsConstructor
public class TbBusinessTrackRecordServiceImpl implements ITbBusinessTrackRecordService {

    private final ITbBusinessService businessService;

    private final TbBusinessTrackRecordMapper tbBusinessTrackRecordMapper;

    private final SysDictDataMapper sysDictDataMapper;

    /**
     * 新增商机跟进
     *
     * @param businessTrackVo
     */
    @Override
    @Transactional
    public void add(BusinessTrackVo businessTrackVo) {
        //前端传递过来的参数一部分需要对商机进行更新,一部分需要新增商机跟进记录
        TbBusiness business = BeanUtil.toBean(businessTrackVo, TbBusiness.class);
        business.setId(businessTrackVo.getBusinessId());
        businessService.updateTbBusiness(business);

        TbBusinessTrackRecord record = BeanUtil.toBean(businessTrackVo, TbBusinessTrackRecord.class);
//        tbBusinessTrackRecordMapper.insert(record);
        String username = SecurityUtils.getUsername();
        record.setCreateBy(username);
        record.setType("0");
        record.setCreateTime(LocalDateTime.now());
        tbBusinessTrackRecordMapper.add(record);
    }

    /**
     * 查询跟进状态
     *
     * @param id
     * @return
     */
    @Override
    public List<TbBusinessTrackRecord> list(Long id) {
        List<TbBusinessTrackRecord> records = tbBusinessTrackRecordMapper.list(id);
        for (TbBusinessTrackRecord record : records) {
            String keyItems = record.getKeyItems();
            List<String> collect = Arrays.stream(keyItems.split(",")).map(key -> {
                return sysDictDataMapper.selectDictLabel("communication_point", key);
            }).collect(Collectors.toList());
            //获取重点集合
            List<String> keys = record.getKeys();
            //将查询到的信息封装
            keys.addAll(collect);
            //返回
            record.setKeys(keys);
        }
        return records;
    }
}
